package com.googlecode.perfectable.persistable.storage.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;

import com.googlecode.perfectable.persistable.DeletingFileVisitor;
import com.googlecode.perfectable.persistable.serialization.Separator;
import com.googlecode.perfectable.persistable.session.Identifier;
import com.googlecode.perfectable.persistable.storage.AbstractSerializingStorage;
import com.googlecode.perfectable.persistable.storage.Persister;

public class FileStorage extends AbstractSerializingStorage {

	private final static String SUFFIX = ".ser";

	private final Path base;

	public FileStorage(Path directory, Separator separator) {
		super(separator);
		this.base = directory;
	}

	public FileStorage(Path base, Separator separator, Persister relationPersister) {
		super(separator, relationPersister);
		this.base = base;
	}

	@Override
	protected FileOutputStream outputStream(Identifier<?> identity) {
		Path path = objectPath(identity);
		try {
			return new FileOutputStream(path.toFile());
		}
		catch(FileNotFoundException e) {
			throw new RuntimeException(e); // MARK
		}
	}

	@Override
	protected InputStream inputStream(Identifier<?> identity) {
		Path path = objectPath(identity);
		try {
			return new FileInputStream(path.toFile());
		}
		catch(FileNotFoundException e) {
			throw new RuntimeException(e); // MARK
		}
	}

	public void purge() throws IOException {
		DeletingFileVisitor.deleteRecursivly(this.base);
	}

	public Path objectPath(Identifier<?> enumerator) {
		return this.base.resolve(enumerator.code() + SUFFIX);
	}
}
